#!/usr/bin/env groovy

//def SUFFIX = "bat"
def SUFFIX = "war"
def TOMCAT_HOME = this.args[0]

def code
def file = new File(".")
def list = []
def no = 1

file.eachFileRecurse {
	if(it.toString().endsWith(SUFFIX)){
		list.add(it.getAbsolutePath())
		println "$no. " + it.getAbsolutePath()
		no++
	}
}

if(list.isEmpty()){
	println "no $SUFFIX file was found"
	return code;
}

println "$no. all war files"
println "0. quit"

def input
System.in.withReader {
	print "Please select war to deploy:"
	input = it.readLine()
	
	while(!(input ==~ "[0-$no]")){
		print "Please select war to deploy:"
		input = it.readLine();
	}
}

if(input.toInteger() == 0){
	println "quit deploy"
	return -1
}

if(input.toInteger() == no){
	// deploy all files
	for(i = 0; i < no - 1; i++){
		code = deploy(list[i], TOMCAT_HOME, SUFFIX)
		if(code != 0){
			break;
		}
	}	
}else{
	// deploy one file
	code = deploy(list[input.toInteger() - 1], TOMCAT_HOME, SUFFIX)
}

return code

def deploy(path, tomcatHome, suffix){
	def file = new File(path.toString());
	def pack = file.getName().split("\\.")[0]
	def code
	
	println "remove previous package $pack ..."
	code = executeCommand("rm -rf $tomcatHome/webapps/$pack")
	if(code != 0){
		println "remove previouse folder failed"
		return code
	}
	println "remove previous package success"
	
	code = executeCommand("rm -rf $tomcatHome/webapps/$pack.$suffix")
	if(code != 0){
		println "remove previouse package failed"
		return code
	}
	
	println "copy $pack.$suffix file ..."
	code = executeCommand("cp $path $tomcatHome/webapps")
	if(code != 0){
		println "copy file failed"
		return code;
	}
	println "copy file success"
	
	return code
}

def executeCommand(String cmd){
	println cmd
	
	def proc = cmd.execute()
	return proc.waitFor()
}